package com.inventory.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.inventory.persistence.Corporation;
import com.inventory.persistence.CorporationExample;
import com.inventory.persistence.dao.CorporationMapper;

public class CorporationServiceImpl implements CorporationService {
	@Autowired
	private CorporationMapper mapper;
	@Autowired
	private AddressService addressService;

	private final static String DEFAULT_CURR_CODE = "INR";

	public int createCorporation(Corporation corporation) {
		if (corporation.getCurrencyCode() == null) {
			corporation.setCurrencyCode(DEFAULT_CURR_CODE);
		}
		addressService.createAddress(corporation.getAddress());
		corporation.setAddressOid(corporation.getAddress().getOid());
		corporation.setVersionStamp(1);
		return mapper.insert(corporation);
	}

	public int updateCorporation(Corporation corporation) {
		addressService.updateAddress(corporation.getAddress());
		corporation.setVersionStamp(corporation.getVersionStamp() + 1);
		return mapper.updateByPrimaryKey(corporation);
	}

	public int deleteCorporation(Corporation corporation) {
		int key = mapper.deleteByPrimaryKey(corporation.getOid());
		addressService.deleteAddress(corporation.getAddress());
		return key;
	}

	public CorporationMapper getMapper() {
		return mapper;
	}

	public void setMapper(CorporationMapper mapper) {
		this.mapper = mapper;
	}

	public AddressService getAddressService() {
		return addressService;
	}

	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}

	public boolean isAnyCorporationExists() {
		CorporationExample example = new CorporationExample();
		example.createCriteria().andOidIsNotNull();
		int count = mapper.countByExample(example);
		return (count == 0) ? false : true;
	}

	@Override
	public List<Corporation> getAllCorporations() {
		CorporationExample example = new CorporationExample();
		example.createCriteria().andOidIsNotNull();
		return mapper.selectByExample(example);
	}

}
